package com.svms.save.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.svms.save.cache.LicenseCache;
import com.svms.save.services.LicenseService;
import com.svms.save.utils.ApplicationContextHelper;
import com.svms.save.utils.WebUtils;
import com.svms.save.vo.LicenseVo;
import com.svms.save.vo.ResultVo;

public class LicenseInterceptor extends HandlerInterceptorAdapter {
	Logger log = LoggerFactory.getLogger(LicenseInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		boolean flag = false;
		LicenseService licenseService = ApplicationContextHelper.applicationContext.getBean(LicenseService.class);
		LicenseVo licen = licenseService.validateLicense(LicenseCache.getLicense(),false);
		if(ResultVo.SUCCESSS.equals(licen.getState())) {
			if(log.isDebugEnabled()) {
				log.debug("License SUCCESS!");
			}
			flag = true;
		}else {
			log.error(String.format("授权无效【%s】",licen.getErrMsg()));
			ResultVo<String> result = ResultVo.createResultVo(ResultVo.LICENSE_ERROR, licen.getErrMsg(), "");
			WebUtils.sendDirectToClient(response, result);
		}
		return flag;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}
}
